import type { Model } from './connect';
import menuMock from '@/constant/menu-mock';
import serveMenuMock from '@/constant/menu-server-mock';
import { generateTree } from '@/utils/utils';
import { resolveDashboardMenu } from '@/utils/menu';

export interface Menu extends Model {
  state: any;
}

const initialState = {
  history: [],
  totalHistory: {
    historyList: [],
    prevHistory: null,
  },
  stars: [],
  menuData: menuMock, // 所有菜单数据
  serveMenu: serveMenuMock, // 接口返回菜单数据
};

export default {
  namespace: 'menu',
  state: initialState,
  effects: {
    // 获取菜单
    *initMenu({ payload: { startMenus } }, { put }) {
      const menuData = startMenus || [];
      menuData.forEach((item: any) => {
        item.key = item.id;
        item.openTabPath = item.path;
      });
      menuData.sort((a: any, b: any) => a.seqNum - b.seqNum);
      let serveMenu = generateTree(menuData, 'parentResourceId', 'children');
      serveMenu = resolveDashboardMenu({
        serveMenu,
      });
      yield put({
        type: 'saveMenu',
        payload: {
          menuData,
          serveMenu,
        },
      });
    },
  },
  reducers: {
    save(state, { payload }: any) {
      return { ...state, ...payload };
    },
    resetState() {
      return initialState;
    },
  },
  subscriptions: {},
} as Menu;
